import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

interface panel {
  company_name: string;
  active: boolean;
  ID: number;
}

@Component({
  selector: 'app-sys-user-shops',
  templateUrl: './shops.component.html'
})
export class SysUserShopsComponent implements OnInit {
  record: any = {};
  i: boolean = false;
  panelOptions = {};
  checkOptions = [] as any;
  op_checked: number[] = [];

  panels: panel[] = [];
  isCheckedAll = false;

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    this.loadData();
  }

  loadData(): void {
    if (this.record.ID > 0) {
      zip(this.http.get(`api/user/${this.record.ID}/shops`), this.http.get(`api/user/${this.record.ID}/company`))
        .pipe(
          finalize(() => {
            this.cdr.detectChanges();
          })
        )
        .subscribe(([shops, companies]: [NzSafeAny, NzSafeAny]) => {
          // 构造数据
          let companyArr = companies.data;
          for (let i = 0; i < companyArr.length; i++) {
            let element = companyArr[i];
            element['active'] = false;
            this.panels.push(element);
            this.panelOptions[element['ID']] = [];
          }
          let shopArr = shops.data;
          for (let i = 0; i < shopArr.length; i++) {
            let shop = shopArr[i];
            this.panelOptions[shop['company_id']].push(shop);
          }
          this.panels[0].active = true;
          this.checkOptions = this.panelOptions[this.panels[0].ID];
          //console.log(this.checkOptions);
          this.logAll();
          this.i = true;
        });
    }
  }

  close(): void {
    this.modal.destroy();
  }

  save(): void {
    //let ids = this.op_checked;
    let ids = this.getCheckIds();
    this.http.put(`api/user/${this.record.ID}/shops`, { shopIds: ids }).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.msgSrv.success(res.msg);
      this.modal.close(true);
    });
  }

  getCheckIds(): number[] {
    //return this.op_checked;
    let allIds = [] as any;
    for (let key in this.panelOptions) {
      for (let op of this.panelOptions[key]) {
        if (op['checked'] == true) {
          allIds.push(op['shop_id']);
        }
      }
    }
    //console.log(allIds);
    return allIds;
  }

  logAll(): void {
    let allIds = [] as any;
    for (let op of this.checkOptions) {
      if (op['checked'] == true) {
        allIds.push(op['shop_id']);
      }
    }
    for (let key in this.panelOptions) {
      for (let op of this.panelOptions[key]) {
        if (op['checked'] == true) {
          allIds.push(op['shop_id']);
        }
      }
    }
    this.log(allIds);
  }

  log(value: any[]): void {
    //console.log(value);
    this.op_checked = value;
  }

  checkChange(checked: boolean, value: any): void {
    //console.log(checked);
    //console.log(value);
    value['checked'] = checked;
    this.logAll();
  }

  checkAll(value: any): void {
    value.stopPropagation();
    var collapseParentNode = null;
    if (value.target.parentNode.parentNode.parentNode.parentNode.tagName.toLowerCase() == 'nz-collapse-panel') {
      collapseParentNode = value.target.parentNode.parentNode.parentNode.parentNode;
    }
    if (value.target.parentNode.parentNode.parentNode.parentNode.parentNode.tagName.toLowerCase() == 'nz-collapse-panel') {
      collapseParentNode = value.target.parentNode.parentNode.parentNode.parentNode.parentNode;
    }
    //console.log(collapseParentNode);
    if (collapseParentNode) {
      //console.log(this.checkOptions);
      if (this.isCheckedAll == false) {
        this.isCheckedAll = true;
      } else {
        this.isCheckedAll = false;
      }

      for (let op of this.checkOptions) {
        if (this.isCheckedAll) {
          op['checked'] = true;
        } else {
          op['checked'] = false;
        }
      }
      this.logAll();
    }
  }

  activeChange(value: number, active: boolean): void {
    if (active) {
      this.checkOptions = this.panelOptions[value];
      this.i = true;
      this.isCheckedAll = false;
    }
  }
}
